package common;

import java.io.*;

public class Measure 
{
	public static long ogm_log, icm_log, ogm_count, icm_count, read_delay, write_delay;
//	private static Object ogm_lock, icm_lock, read_lock, write_lock;
	
	public static void initializeProcessMeasures()
	{
//		read_lock = new Object();
//		write_lock = new Object();
		read_delay = 0;
		write_delay = 0;
	}
	
	public static void initializeMessageMeasures()
	{
//		ogm_lock = new Object();
//		icm_lock = new Object();
		ogm_log = 0;
		icm_log = 0;
		ogm_count = 0;
		icm_count = 0;
	}
	

	public static void incrimentICM(Serializable o)
	{
		byte[] bytes = new byte[0];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try
		{
			ObjectOutputStream oos = new ObjectOutputStream(bos); 
			oos.writeObject(o);
			oos.flush(); 
			oos.close(); 
			bos.close();
			bytes = bos.toByteArray ();
		}
		catch (Exception ex)
		{}
//		synchronized(icm_lock)
//		{
			icm_log += bytes.length;
			icm_count++;
//		}
	}
	
	public static void incrimentOGM(Serializable o)
	{
		byte[] bytes = new byte[0];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try
		{
			ObjectOutputStream oos = new ObjectOutputStream(bos); 
			oos.writeObject(o);
			oos.flush(); 
			oos.close(); 
			bos.close();
			bytes = bos.toByteArray ();
		}
		catch (Exception ex)
		{}
//		synchronized(ogm_lock)
//		{
			ogm_log += bytes.length;
			ogm_count++;
//		}
	}
	
	public static void accumulate_read_delay( long delay_ms )
	{
//		synchronized(read_lock)
//		{
			read_delay += delay_ms;
//		}
	}
	
	public static void accumulate_write_delay( long delay_ms )
	{
//		synchronized(read_lock)
//		{
			write_delay += delay_ms;
//		}
	}
	
	public static void print_result(){
		System.out.println( "\n:::: simulation results ::::" );
		System.out.println( "ogm_log: " + ogm_log );
		System.out.println( "ogm_count: " + ogm_count );
		System.out.println( "icm_log: " + icm_log );
		System.out.println( "icm_count: " + icm_count );
		System.out.println( "read delay: " + read_delay );
		System.out.println( "write delay: " + write_delay );		
	}
	
	public static void result_log( String filename, String settings ){
		try{
			BufferedWriter out = new BufferedWriter( new FileWriter( filename ) );
			
			String s = ":::: simulation settings ::::\n";
			s += settings;
			s += "\n:::: simulation results ::::";
			s += "\nogm_log: " + ogm_log;
			s += "\nogm_count: " + ogm_count;
			s += "\nicm_log: " + icm_log;
			s += "\nicm_count: " + icm_count;
			s += "\nread delay: " + read_delay;
			s += "\nwrite delay: " + write_delay;

			out.write(s); out.newLine();
			
			out.close();
			////////////////////////////////////////////////////////////////
		}catch( IOException e ){
			System.err.println( "Measure: file write err" );
		}
		return;
	}
}